var express = require('express');
var router = express.Router();
var db=require('../model/db')

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});
// 首页后端逻辑
router.get('/index',async (req,res)=>{
  let sql='select * from stu_score';
  let [err,data]=await db.query(sql);
  if(err){
    res.send({ "code": "500", "msg": "查询失败" })
  } else {
    res.send({ "code": "200", "msg": "查询成功", "data": data })
  }
  
})
// 添加页逻辑
router.get('/add',async(req,res)=>{
  // res.render('add.html');
  let sql='select * from stu_score';
  let [err,data]=await db.query(sql);
  if(err){
    res.send({ "code": "500", "msg": "查询失败" })
  } else {
    res.send({ "code": "200", "msg": "查询成功", "data": data })
  }
})
// 添加页面的操作
router.post('/add',async (req,res)=>{
  let {name,age,sex,claass,score}=req.body; 
   let sql=`insert into stu_score (name,age,sex,class,score) value ('${name}',${age},'${sex}',${claass},${score})`;
   let [err,data]=await db.query(sql);
   if(err){
     res.send({ "code": "500", "msg": "查询失败" })
   } else {
     res.send({ "code": "200", "msg": "查询成功", "data": data })
   }
})
// 修改页面的数据
router.post("/edit", async (req, res) => {
  let {id} = req.body;
  console.log(req.body);
  let sql = `select * from stu_score where id=${id}`;
  console.log(sql);
  //执行sql语句
  let [err,data]=await db.query(sql);
   if(err){
     res.send({ "code": "500", "msg": "修改失败" })
   } else {
     res.send({ "code": "200", "msg": "修改成功", "data": data })
   }
})
// 删除页面的数据
router.post('/del',async (req,res)=>{
  let {id} = req.body;
  console.log(req.body);
  let sql = `delete from stu_score where id=${id}`;
  console.log(sql);
   let [err,data]=await db.query(sql);
   if(err){
     res.send({ "code": "500", "msg": "删除失败" })
   } else {
     res.send({ "code": "200", "msg": "删除成功", "data": data })
   }
})
/* router.post('/edit',(req,res)=>{
  let {name,age,sex,claass,score,id}=req.body;
  console.log(name,age,sex,claass,score);
  let sql=`update stu_score set name='${name}',age=${age},sex='${sex}',class=${claass},score=${score} where id=${id}`;
  console.log(sql);
  conn.query(sql,(err,doc)=>{
    if(err){
      console.log('修改失败');
    }else{
      console.log(doc);
      res.redirect('/index')
    }
  })
}) */
module.exports = router;
